import { BASE_URL } from '../config';
import store from '../store';
import { makeObjectClean } from '../utils';
import { currentPageUrl } from '../utils/route';
import debug from '../utils/log';

export default function request(options = {}) {
  const {
    url = '',
    method = 'GET',
    data = {}, // GET请求参数
    header,
    skipToast = false, // 是否在ok为false的时候打印错误信息
    needAuth = false, // 是否需要携带token
    showLoading = false, // 请求过程中展示loading
    loadingText = '加载中', // Loading提示
    errorText = '服务器繁忙', // 请求错误的时候输出的文字
    allowDebug = true, // 是否打印调试日志
  } = options;

  // 统一注入约定的header
  let newHeader = { ...header };
  if (needAuth && store.getters.token) {
    newHeader = { Authorization: `${store.getters.token}`, ...header };
  }
  allowDebug && debug('http', `${url} params`, data);
  return new Promise((resolve, reject) => {
    if (showLoading) store.commit('showLoading', { text: loadingText });
    const hasHttp = /^(http|https)/g.test(url);
    uni.request({
      method,
      url: hasHttp ? url : BASE_URL + url,
      data: makeObjectClean(data),
      header: newHeader,
      success: res => {
        const { data = {}, statusCode } = res;
        allowDebug && debug('http', `${url} response`, res);
        // 未登录
        if (statusCode === 401) {
          // 防止多个接口401，多次打开登录页面
          const currentUrl = currentPageUrl();
          if (currentUrl && currentUrl.indexOf('/pages/login/index') > -1) return;
          uni.showToast({ title: '尚未登录，请先登录书城', icon: 'none' });
          setTimeout(() => {
            const redirect = encodeURIComponent(currentUrl) || '';
            const redirectParma = `?redirect=${redirect}&type=navigateBack`;
            uni.navigateTo({ url: `/pages/login/index${redirectParma}` });
          }, 2000);
          return;
        }
        // ok 为 false 时候自动打印错误信息
        const showToast = !skipToast && !data.ok
        if (showToast) uni.showToast({ title: data.msg || '服务器繁忙', icon: 'none' });
        resolve(data);
      },
      fail: err => {
        allowDebug && debug('http', `${url} response`, err);
        if (!skipToast) uni.showToast({ title: errorText, icon: 'none' });
        reject(err);
        // TODO 日志统计
      },
      complete: () => {
        if (showLoading) store.commit('hideLoading');
      }
    });
  });
}
